import {Injectable} from '@nestjs/common';
import {InjectRepository} from "@nestjs/typeorm";

import {Repository} from "typeorm";
import {SurveyEntity} from "../entities/Survey.entity";
import {SurveyQuestionEntity} from "../entities/SurveyQuestion.entity";
import {QuestionEntity} from "../entities/Question.entity";
import {OptionEntity} from "../entities/Option.entity";
import {CreateSurveyDto} from "../dto/CreateSurveyDto";


@Injectable()
export class ManageService {
  constructor(
    @InjectRepository(SurveyEntity)
    private readonly surveyRepository: Repository<SurveyEntity>,
    @InjectRepository(QuestionEntity)
    private readonly questionRepository: Repository<QuestionEntity>,
    @InjectRepository(OptionEntity)
    private readonly optionRepository: Repository<OptionEntity>,
    @InjectRepository(SurveyQuestionEntity)
    private readonly surveyQuestionRepository: Repository<SurveyQuestionEntity>,) {
  }


  /**
   * 创建问卷
   * @param createSurveyDto
   */
  async createSurveyWithQuestionsAndOptions(createSurveyDto: CreateSurveyDto) {
    const survey = new SurveyEntity();
    survey.surveyName = createSurveyDto.surveyName;
    survey.surveySubtitle = createSurveyDto.surveySubtitle;
    survey.createdAt = new Date(); // 设置创建时间
    survey.updatedAt = new Date(); // 设置修改时间

    await this.surveyRepository.save(survey);

    for (let questionDto of createSurveyDto.questions) {
      const questionObj = questionDto.question;

      const question = new QuestionEntity();
      question.questionText = questionObj.questionText;
      question.questionType = questionObj.questionType
      await this.questionRepository.save(question);

      const options = questionObj.options.map(optionDto => this.optionRepository.create({
        ...optionDto,
        question,
      }));
      await this.optionRepository.save(options);

      const surveyQuestion = this.surveyQuestionRepository.create({
        surveyId: survey.id,
        questionId: question.id,
        surveyOrder: questionDto.surveyOrder,
      });
      await this.surveyQuestionRepository.save(surveyQuestion);
    }

    return survey;
  }

  /**
   * 查询所有问卷
   */
  async findAllSurvey() {
    return this.surveyRepository.find({
      relations: [
        'questions', // 从Survey到SurveyQuestion的关联
        'questions.question', // 从SurveyQuestion到Question的关联
        'questions.question.options', // 从Question到Option的关联
      ],
    });
  }

  /**
   * 删除问卷
   * @param surveyId
   */
  async deleteSurveyById(surveyId: string) {
    try {
      // 确保调查存在
      const survey = await this.surveyRepository.findOne({
        where: {
          id: surveyId
        },
        relations: ['questions', 'questions.question', 'questions.question.options'],
      });
      if (!survey) {
        throw new Error(`Survey with id ${surveyId} not found.`);
      }

      // 删除与该调查关联的所有问题
      for (const question of survey.questions) {
        // 删除问题下的所有选项
        const optionsToDelete = await this.optionRepository.find({where: {question}});
        console.log("optionsToDelete", optionsToDelete)
        // await this.optionRepository.remove(optionsToDelete);
        //
        // // 然后删除问题
        // await this.questionRepository.remove(question);
      }

      // 最后，删除调查
      // await this.surveyRepository.remove(survey);
    } catch (error) {
      console.log(error)
      throw error; // 重新抛出异常，以便上层可以处理
    }
  }


  /**
   * 根据surveyId更新问卷
   * @param surveyId
   * @param updateSurveyDto
   */
  async updateSurveyById(surveyId: string, updateSurveyDto: CreateSurveyDto) {

    const survey = await this.surveyRepository.findOne({
      where: {
        id: surveyId
      },
      relations: ['questions', 'questions.question', 'questions.question.options'],
    });

    console.log("survey", survey)

    if (!survey) {
      throw new Error(`Survey with id ${surveyId} not found.`);
    }

    // 更新调查问卷的属性
    survey.surveyName = updateSurveyDto.surveyName || survey.surveyName;
    survey.surveySubtitle = updateSurveyDto.surveySubtitle || survey.surveySubtitle;
    survey.updatedAt = new Date(); // 更新修改时间

    await this.surveyRepository.save(survey);

    // 更新或删除问题
    for (let questionDto of updateSurveyDto.questions) {
      const questionObj = questionDto.question;
      let question;

      if (questionDto.questionId) {
        // 如果存在问题 ID，则更新问题
        // question = await this.questionRepository.findOne(questionDto.questionId);

        if (!question) {
          throw new Error('Question not found');
        }

        question.questionText = questionObj.questionText || question.questionText;
        question.questionType = questionObj.questionType || question.questionType;
        await this.questionRepository.save(question);
      } else {

        // 否则创建新问题
        question = new QuestionEntity();
        question.questionText = questionObj.questionText;
        question.questionType = questionObj.questionType;
        await this.questionRepository.save(question);
      }
    }
  }
}

